home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news
- From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
- Newsgroups: comp.lang.c++
- Subject: Re: Deep/Shallow Copying?
- Date: Thu, 11 Jan 1996 10:31:09 +0100
- Organization: Fachbereich Informatik, TH Darmstadt
- Message-ID: <30F4D8DD.167EB0E7@intellektik.informatik.th-darmstadt.de>
- References: <4d1bhe$1lto@bocanews.bocaraton.ibm.com>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b4 (X11; I; SunOS 4.1.3 sun4m)
-
- pani@genius.tisl.soft.net wrote:
- >
- > Hi Guys,
- > What is Deep copying or Shallow copying? Is this something
- > to do with a Copy constructor?
- > Thanks for any help.
- >
-
- I'm not for sure if this expression is often used in _C++_. Anyway ...
- A shallow copy just copies the data-members of a class by memberwise
- copying each of them. Deep copying does some additional work, e.g.
- replicating associated data. The easiest example that outlines the
- difference is a class that maintains a single pointer:
-
- struct A {
- A() : a_(new char('a')) {}
- ~A() { delete a_; }
- char* a_;
- };
-
- The compiler-provided default copy-ctor does a shallow copy and so
- only the pointer-value not its related data is copied. Thus
-
- A a; A a,b
- A b(a); or b=a;
-
- will cause problems when 'a' and 'b' get destructed because they share
- the same 'char'-instance. To remove the problem one provides a suitable
- copy-ctor and assignment-op:
-
- struct A {
- A() : a_(new char('a')) {}
- A(const A& a) : a_(new char(*a.a_)) {}
- A& operator = (const A& a) {
- if (this!=&a) { delete a_; a_=new char(*a.a_); }
- return *this;
- }
- ~A() { delete a_; }
- char* a_;
- };
-
- Now a deep copy is created, ie. the related char-instance is also
- duplicated.
- So, you get the shallow-copy for free in C++, but a deep-copy needs
- mostly
- some additional code.
-
- Enno
-